package com.ffapp.helper.user;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.BleLog;
import com.clj.fastble.utils.HexUtil;
import com.ffapp.helper.R;
import com.ffapp.helper.basis.BasisActivity;
import com.ffapp.helper.basis.BasisApp;
import com.ffapp.helper.basis.Constants;
import com.ffapp.helper.common.ObserverManager;
import com.ffapp.helper.eventbus.PopHandleMessage;
import com.ffapp.helper.login.LoginActivity;
import com.ffapp.helper.mservice.HeartService;
import com.ffapp.helper.util.CountDown;
import com.ffapp.helper.util.MessageUtil;
import com.ffapp.helper.view.PopHandle;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.leon.lfilepickerlibrary.LFilePicker;
import com.leon.lfilepickerlibrary.utils.Constant;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.params.ProgressParams;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import my.BleUtils;
import my.ByteUtils;
import my.DialogUtils;
import my.FileUtils;

public class WareSoftUpdateActivity extends BasisActivity {   private boolean isFinish = false;
    private boolean isDestroy = false;
    @BindView(R.id.tv_content)
    TextView tvContent;

    private CircleDialog.Builder builder;

    private static String UPGRADE_NOTICE = "4e";
    private static String DATA_ASK = "52";
    private static String SEND_FILE_DATA = "46";
    private CountDown mCountDownTimer;
    private CountDown mSendFileDataTimer;
    private static final long MAX_TIME = 25 * 1000;

    private int packetCount;   //请求包的个数

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.activity_ware_soft_update);
        setTitle("固件升级");
        setTitleLeftButton(R.drawable.base_icon_back_white, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initCountDownTimer();
        isDestroy = false;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
    }

    private int curPacketCount = 0;   //当前分包数
    private int packetIndex = 0;           //当前请求的升级包索引
    @SuppressLint("HandlerLeak")
    private Handler submitHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
//                case 80://75提交
//                    BleLog.d("报文返回=submitHandler==curPacketCount"+curPacketCount);
//                    BleLog.d("报文返回=submitHandler==packetCount"+packetCount);
//                    if (curPacketCount < packetCount && isFinish == false) {
//                        BleLog.d("submitHandler==进来了");
//                        curPacketCount++;
//                        sendFileData();
//                    }
//                    break;
                case 76:  //检查是否传输完毕
                    try {
                        if (!isFinish && !isDestroy) {
                            showToast("设置失败，请重试");
                            BleUtils.stopNotify();
                            isFinish = true;
                        }
                    } catch (NullPointerException e) {
                        throw e;
                    }
                    break;
                case 81:
                    BleUtils.stopNotify();
                    mCountDownTimer.cancel();
                    isFinish = true;
                    break;
            }
        }
    };

    public void initCountDownTimer() {
        mCountDownTimer = new CountDown();
        mCountDownTimer.setMillisInFuture(MAX_TIME);
        mCountDownTimer.setCountdownInterval(1000);
        mCountDownTimer.setCountDownListener(new CountDown.CountDownListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onFinish() {
                submitHandler.sendEmptyMessage(Constants.CHECK_FINISH);
            }

            @Override
            public void onTick(long millisUntilFinished) {
//                mTimerTv.setText(TimeTools.getCountTimeByLong(millisUntilFinished));
            }
        });
        mSendFileDataTimer = new CountDown();
        mSendFileDataTimer.setMillisInFuture(100);
        mSendFileDataTimer.setCountdownInterval(1000);
        mSendFileDataTimer.setCountDownListener(new CountDown.CountDownListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onFinish() {
                sendFileData();
            }

            @Override
            public void onTick(long millisUntilFinished) {
//                mTimerTv.setText(TimeTools.getCountTimeByLong(millisUntilFinished));
            }
        });
    }


    @OnClick(R.id.btn_update)
    public void update() {
        fileTotal = 0;
        String file_media = Constants.DIR_FIRM_WARE;
        File destDir = new File(file_media);
        if (!destDir.exists()) {// 判断文件夹是否存在
            destDir.mkdirs();
        }
        new LFilePicker()
                .withActivity(WareSoftUpdateActivity.this)
                .withRequestCode(REQUEST_FIRM_WARE_SHARE)
                .withTitle("文件选择")
                .withBackgroundColor("#0396FF")
                .withMutilyMode(false)
                .withMaxNum(1)
                .withStartPath(Constants.DIR_FIRM_WARE)//指定初始显示路径
                .withFileFilter(new String[]{"txt", "bin"})
                .start();
    }

    private final static int REQUEST_FIRM_WARE_SHARE = 42;        //从固定文件夹返回

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//            tvContent.setVisibility(View.VISIBLE);
//            showToast("升级成功");
        if (requestCode == REQUEST_FIRM_WARE_SHARE && resultCode == Activity.RESULT_OK) {//是否选择，没选择就不会继续
            String path = null;
            List<String> list = data.getStringArrayListExtra(Constant.RESULT_INFO);
            if (list == null || list.size() == 0) {
            } else {
                path = list.get(0);
            }
            if (TextUtils.isEmpty(path)) {
                DialogUtils.DialogOkMsg(mContext, "读取文档失败");
                return;
            }
            openOrSend(path);
        }
    }

    public void openOrSend(final String path) {
        DialogUtils.DialogStringList(mContext, new String[]{"查看", "发送"}, new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    FileUtils.openFile(new File(path), mContext);
                } else {
//                    stopService(new Intent(WareSoftUpdateActivity.this, HeartService.class));
                    openBleNotify(path, UPGRADE_NOTICE);
                }
            }
        });
    }

    private  List<Byte> upResult;
    private void openBleNotify(final String filePath, final String type) {
        upResult = new ArrayList<>();
        isFinish = false;
        BleUtils.notify(mContext,new BleNotifyCallback() {
            @Override
            public void onNotifySuccess() {
                sendProtocolUpdate(filePath);
            }

            @Override
            public void onNotifyFailure(BleException exception) {
//                        BleLog.d("下发设置打开通知操作失败");
            }

            @Override
            public void onNotifyFailure(String message) {
                showToast(message);
                dismissProgress();
            }

            @Override
            public void onCharacteristicChanged(byte[] data) {
                String sMes = HexUtil.bytesToAscii(data);
                BleLog.d("报文返回==" + HexUtil.bytesToHexString(data));
                for (Byte a : data) {
                    upResult.add(a);
                }

//                BleLog.d("报文返回=head=" + HexUtil.bytesToHexString(data[0]));
                if (HexUtil.bytesToHexString(upResult.get(0)).contains("FE") || HexUtil.bytesToHexString(upResult.get(0)).contains("fe") &&
                        HexUtil.bytesToHexString(upResult.get(upResult.size()-1)).contains("FE") || HexUtil.bytesToHexString(upResult.get(upResult.size()-1)).contains("fe") && upResult.size()>2) {
                    String funCode = HexUtil.bytesToHexString(upResult.get(2));  //功能码
                    BleLog.d("报文返回=功能码=" + funCode);
                    switch (funCode) {
                        case "52":  //DATA_ASK        //升级数据请求 0x52 上行
                            packetCount = upResult.get(5);   //请求分包的个数
                            BleLog.d("报文返回=packetCount=" + packetCount);
                            byte[] packetIndexByte = new byte[2];
                            packetIndexByte[0] = upResult.get(3);
                            packetIndexByte[1] = upResult.get(4);
                            packetIndex = ByteUtils.byte2int(packetIndexByte);   //当前请求的升级包索引
                            BleLog.d("报文返回=packetIndex=" + packetIndex);
                            curPacketCount = 0;
//                            submitHandler.sendEmptyMessage(80);
                            sendFileData();
                            break;
                        case "47":  //升级结果应答 0x47 上行
                            PopHandle popHandle = null;
                            switch (upResult.get(3)) {
                                case 0:
                                    popHandle = new PopHandle(WareSoftUpdateActivity.this, "tips_fail", "提示", "升级失败");
                                    break;
                                case 1:
                                    popHandle = new PopHandle(WareSoftUpdateActivity.this, "tips_fail", "提示", "升级成功");
                                    builder.create().dismiss();
                                    break;
                            }
                            popHandle.show();
                            mCountDownTimer.cancel();
                            BleUtils.stopNotify();
                            break;
                    }
                }
            }

            @Override
            public void onError() {
                //关闭监听
                isFinish = true;
            }

            @Override
            public void onReconSuc(String message) {
                dismissProgress();
                showToast(message);
            }
        });

    }

    private int fileTotal;
    private void sendProtocolUpdate(String data) {
        upResult.clear();
        builder = new CircleDialog.Builder(WareSoftUpdateActivity.this);
        builder.setCancelable(false).setCanceledOnTouchOutside(false)
                .configDialog(params -> params.backgroundColor = Color.WHITE)
                .setTitle("升级中")
                .setProgressText("下发进度")
//                        .setProgressText("已经下载%s了")
//                        .setProgressDrawable(R.drawable.bg_progress_h)
                .setNegative("取消", v -> submitHandler.sendEmptyMessage(81));
        builder.show();
        mCountDownTimer.start();
        String a = Arrays.toString(MessageUtil.getUpgradeNotice(data));
        String b = HexUtil.bytesToHexString(MessageUtil.getUpgradeNotice(data));
        BleUtils.write(MessageUtil.getUpgradeNotice(data), new BleWriteCallback() {
            @Override
            public void onWriteSuccess(int current, int total, byte[] justWrite) {
                fileTotal = MessageUtil.getFileTotal();
            }

            @Override
            public void onWriteFailure(BleException exception) {

            }
        });
    }

    private int allTotal;
    private void sendFileData() {
        if (curPacketCount < packetCount && isFinish == false) {
            curPacketCount++;
            allTotal = 0;
            upResult.clear();
            mCountDownTimer.start();
            int packetIndexs = packetIndex + curPacketCount - 1;
            if(fileTotal != 0){
                builder.setProgress(fileTotal, packetIndexs).create();
                if (packetIndexs >= fileTotal) {
                    builder.setProgressText("下载完成").create();
                };
            }
            BleLog.d("报文输出====" +HexUtil.bytesToHexString(MessageUtil.sendFileData(packetIndexs)) );
            BleUtils.write(MessageUtil.sendFileData(packetIndexs), new BleWriteCallback() {
                @Override
                public void onWriteSuccess(int current, int total, byte[] justWrite) {
                    allTotal++;
//                    BleLog.d("报文返回=onWriteSuccess== allTotal==" +allTotal );
//                    BleLog.d("报文返回=onWriteSuccess== current=="+current);
//                    BleLog.d("报文返回=onWriteSuccess== total==" +total);
//                BleLog.d("报文返回=onWriteSuccess== justWrite==" + Arrays.toString(justWrite));
                    //ble最多发送20字节，而现在要一次要发送200字节 就要分组发送
                    if (allTotal == total) {
//                        if(packetCount >1){
//                            submitHandler.sendEmptyMessageDelayed(80, 400);
//                        }else {
//                            submitHandler.sendEmptyMessage(80);
//                        }
                        mSendFileDataTimer.start();
                    }
                }

                @Override
                public void onWriteFailure(BleException exception) {

                }
            });
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isDestroy = true;
        submitHandler.sendEmptyMessage(81);
    }

    private boolean isFront = false;

    @Override
    protected void onResume() {
        super.onResume();
        isFront = true;
    }
    @Override
    protected void onPause() {
        super.onPause();
        isFront = false;
    }
    @Override
    public void onMessageEvent(PopHandleMessage event) {
        BleLog.d("报文返回= PopHandleMessage  =="+ event.getMessage());
        super.onMessageEvent(event);
        if(isFront){
            LoginActivity.toLoadingAllClear(BasisApp.getInstance());
        }
    }
}
